import { defineStore } from 'pinia';
import { showToast } from '@/utils/toast';

// 系统设置状态仓库
export const useSystemStore = defineStore('system', {
  state: () => ({
    // 系统设置数据
    settings: {
      basic: {
        systemName: '',
        version: '',
        description: '',
        defaultLanguage: 'zh-CN',
        dateFormat: 'YYYY-MM-DD',
        showWelcomeMessage: true
      },
      security: {
        passwordPolicy: {
          minLength: 8,
          expireDays: 90,
          requireUppercase: true,
          requireLowercase: true,
          requireNumber: true,
          requireSpecialChar: false
        },
        login: {
          maxFailedAttempts: 5,
          lockoutMinutes: 15,
          enableCaptcha: true,
          enableTwoFactor: false
        }
      },
      notifications: {
        channels: {
          email: {
            enabled: true,
            smtpServer: '',
            smtpPort: 587,
            encryption: 'tls',
            senderEmail: ''
          },
          system: {
            enabled: true
          }
        },
        triggers: {
          userRegistration: true,
          passwordChange: true,
          loginAlert: true,
          systemUpdates: true
        }
      },
      backup: {
        autoBackup: {
          enabled: true,
          frequency: 'daily',
          time: '02:00',
          retentionDays: 30
        },
        storage: {
          local: {
            enabled: true,
            path: '/var/backups/'
          },
          cloud: {
            enabled: false,
            provider: 'aws',
            accessKey: '',
            secretKey: '',
            bucket: ''
          }
        }
      },
      logs: {
        logLevel: 'info',
        retentionDays: 30,
        eventTypes: {
          userActions: true,
          systemEvents: true,
          errors: true,
          securityEvents: true,
          apiRequests: false,
          performance: false
        },
        storage: {
          file: true,
          database: false,
          externalService: false
        }
      }
    },
    
    // 系统统计信息
    stats: {
      users: 0,
      roles: 0,
      permissions: 0,
      storageUsed: 0,
      storageTotal: 0
    },
    
    // 加载状态
    loading: {
      settings: false,
      save: false,
      backup: false,
      logs: false
    },
    
    // 系统版本信息
    versionInfo: {
      current: '',
      latest: '',
      updateAvailable: false
    },
    
    // 备份状态
    backupStatus: {
      lastBackup: '',
      status: 'idle', // idle, running, completed, failed
      progress: 0
    }
  }),

  getters: {
    // 获取系统名称
    getSystemName: (state) => state.settings.basic.systemName || '管理系统',
    
    // 获取存储使用率
    getStorageUsagePercentage: (state) => {
      if (state.stats.storageTotal === 0) return 0;
      return Math.round((state.stats.storageUsed / state.stats.storageTotal) * 100);
    },
    
    // 检查是否需要显示更新通知
    shouldShowUpdateNotification: (state) => {
      return state.versionInfo.updateAvailable;
    }
  },

  actions: {
    /**
     * 获取系统设置
     */
    async getSystemSettings() {
      try {
        this.loading.settings = true;
        const response = await requestInstance.get('system/settings');
        // 合并获取到的设置与本地设置
        Object.assign(this.settings, response.data || {});
        return this.settings;
      } catch (error) {
        console.error('获取系统设置失败:', error);
        showToast('获取系统设置失败', 'error');
        return this.settings;
      } finally {
        this.loading.settings = false;
      }
    },

    /**
     * 保存系统设置
     * @param {Object} settings - 设置数据
     */
    async saveSystemSettings(settings) {
      try {
        this.loading.save = true;
        const response = await requestInstance.post('system/settings', settings);
        
        // 更新本地设置
        Object.assign(this.settings, response.data || settings);
        
        showToast('系统设置保存成功', 'success');
        return this.settings;
      } catch (error) {
        console.error('保存系统设置失败:', error);
        showToast(error.response?.data?.message || '保存系统设置失败', 'error');
        throw error;
      } finally {
        this.loading.save = false;
      }
    },

    /**
     * 获取系统统计信息
     */
    async getSystemStats() {
      try {
        const response = await requestInstance.get('system/stats');
        this.stats = response.data || this.stats;
        return this.stats;
      } catch (error) {
        console.error('获取系统统计信息失败:', error);
        return this.stats;
      }
    },

    /**
     * 触发手动备份
     */
    async triggerManualBackup() {
      try {
        this.loading.backup = true;
        this.backupStatus.status = 'running';
        this.backupStatus.progress = 0;
        
        const response = await requestInstance.post('system/backup');
        
        // 更新备份状态
        this.backupStatus.status = 'completed';
        this.backupStatus.progress = 100;
        this.backupStatus.lastBackup = new Date().toISOString();
        
        showToast('系统备份成功', 'success');
        return response.data;
      } catch (error) {
        console.error('系统备份失败:', error);
        this.backupStatus.status = 'failed';
        showToast(error.response?.data?.message || '系统备份失败', 'error');
        throw error;
      } finally {
        this.loading.backup = false;
      }
    },

    /**
     * 查看系统日志
     */
    async viewLogs() {
      try {
        this.loading.logs = true;
        const response = await requestInstance.get('system/logs');
        
        // 这里可以根据需要处理日志数据，例如打开日志查看器
        // 目前只是返回日志数据
        return response.data;
      } catch (error) {
        console.error('获取系统日志失败:', error);
        showToast('获取系统日志失败', 'error');
        throw error;
      } finally {
        this.loading.logs = false;
      }
    },

    /**
     * 清理系统日志
     * @param {number} days - 保留多少天的日志
     */
    async cleanLogs(days = 30) {
      try {
        this.loading.logs = true;
        await requestInstance.post('system/logs/clean', { days });
        
        showToast('系统日志清理成功', 'success');
        return true;
      } catch (error) {
        console.error('清理系统日志失败:', error);
        showToast('清理系统日志失败', 'error');
        throw error;
      } finally {
        this.loading.logs = false;
      }
    },

    /**
     * 检查系统更新
     */
    async checkForUpdates() {
      try {
        const response = await requestInstance.get('system/check-updates');
        this.versionInfo = response.data || this.versionInfo;
        
        if (this.versionInfo.updateAvailable) {
          showToast('发现系统更新', 'info');
        }
        
        return this.versionInfo;
      } catch (error) {
        console.error('检查系统更新失败:', error);
        return this.versionInfo;
      }
    },

    /**
     * 重置系统设置为默认值
     */
    async resetToDefaults() {
      try {
        this.loading.save = true;
        const response = await requestInstance.post('system/settings/reset');
        
        // 更新本地设置为默认值
        Object.assign(this.settings, response.data || {});
        
        showToast('系统设置已重置为默认值', 'success');
        return this.settings;
      } catch (error) {
        console.error('重置系统设置失败:', error);
        showToast('重置系统设置失败', 'error');
        throw error;
      } finally {
        this.loading.save = false;
      }
    },

    /**
     * 获取系统健康状态
     */
    async getSystemHealth() {
      try {
        const response = await requestInstance.get('system/health');
        return response.data;
      } catch (error) {
        console.error('获取系统健康状态失败:', error);
        return { status: 'error' };
      }
    }
  }
});